package com.jsbb.controller.tool;

import com.jsbb.core.Message;
import com.jsbb.dto.tool.ApiDto;
import com.jsbb.dto.tool.ApiExportDto;
import com.jsbb.dto.tool.ApiQueryDto;
import com.jsbb.util.SwaggerUtils;
import com.jsbb.util.WordUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 接口文档Controller
 *
 * @author jsbb
 */
@RestController
@RequestMapping("/tool/api")
@Tag(name = "2.1 工具管理-接口文档")
public class ApiController {

    @PostMapping("/list")
    @Operation(summary = "获取列表")
    public Message<List<ApiDto>> list(@RequestBody ApiQueryDto queryDto) {
        if (!StringUtils.hasText(queryDto.getSwaggerUrl())) {
            queryDto.setSwaggerUrl("http://localhost:8080");
        }
        queryDto.setSwaggerUrl(queryDto.getSwaggerUrl().replace("/swagger-ui.html", "").replace("/doc.html", ""));
        List<ApiDto> list = SwaggerUtils.getSwaggerData(queryDto.getSwaggerUrl());
        if (StringUtils.hasText(queryDto.getUrl())) {
            list = list.stream().filter(s -> s.getUrl().contains(queryDto.getUrl())).collect(Collectors.toList());
        }
        if (StringUtils.hasText(queryDto.getTitle())) {
            list = list.stream().filter(s -> (s.getTags() + s.getTitle()).contains(queryDto.getTitle())).collect(Collectors.toList());
        }
        list.sort(Comparator.comparing(ApiDto::getTags));
        return Message.success(list);
    }

    @PostMapping("/export")
    @Operation(summary = "导出")
    public void export(@Validated @RequestBody ApiExportDto queryDto, HttpServletResponse response) throws Exception {
        if (!StringUtils.hasText(queryDto.getSwaggerUrl())) {
            queryDto.setSwaggerUrl("http://localhost:8080");
        }
        queryDto.setSwaggerUrl(queryDto.getSwaggerUrl().replace("/swagger-ui.html", "").replace("/doc.html", ""));
        List<ApiDto> list = SwaggerUtils.getSwaggerData(queryDto.getSwaggerUrl());
        list = list.stream().filter(s -> queryDto.getUrlList().contains(s.getUrl())).collect(Collectors.toList());
        Map<String, List<ApiDto>> map = list.stream().collect(Collectors.groupingBy(e -> e.getTags(), TreeMap::new, Collectors.toList()));
        WordUtils.exportSwagger(map, response);
    }
}
